import { debug } from "./log";

function createRouteRuleMap(routeRules: any[] = []) {
  const routeRuleMap = routeRules.map((routeRule: string = "/") => ({
    rule: routeRule,
    test: (p: string) => {
      if (/\*.+/.test(p) === true) {
        console.error(
          `[useRoute] routeRules - ${routeRule} 格式错误：eg. /prefix_url or /prefix_url/* `
        );
        return 0;
      }

      if (!routeRule.endsWith("*")) {
        return routeRule === p ? Infinity : 0;
      } else {
        let m = p.match(new RegExp(`${routeRule.slice(0, -2)}($|\/.*$)`));
        // eg. /prefix_url/* , /prefix_url/xxx/*
        return m ? (m[0] === p ? routeRule.split("/").length : 0) : 0;
      }
    },
  }));

  return routeRuleMap;
}
export const getMatchItem = (_routeRuleMap:any, pathname:string) => {
  let routeRule = createRouteRuleMap(Object.keys(_routeRuleMap))
  debug({ routeRule })
  let routePath = pathname;
  const machedRule = () => {
    let maxSplitLen = 0; // 只取最长
    let maxRule: string;
    // 按照匹配权重，降序排列
    const matchedList = routeRule
      .map(({ rule, test }) => {
        const splitLen = test(routePath);
        if (maxSplitLen < splitLen) {
          maxSplitLen = splitLen;
          maxRule = rule;
        }

        return splitLen > 0 ? { rule, splitLen } : undefined;
      })
      .filter((i) => !!i)
      .sort((a:any, b:any) => Number(b.splitLen) - Number(a.splitLen));

    return maxRule;
  };
  let machedRuleKey = machedRule();
  let proj = _routeRuleMap[machedRuleKey  as unknown as string];

  if (proj && proj.exclude) {
    if (proj.exclude.includes(pathname)) {
      return null;
    }
  }
  return _routeRuleMap[machedRuleKey as unknown as string];

}